package com.j2ee.ex.user.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.j2ee.ex.db.user.DB;
import com.j2ee.ex.user.pojo.User;
import com.j2ee.ex.user.service.UserService;


public class UserServiceImpl implements UserService {

	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	
	public UserServiceImpl() {
		conn = DB.connect();
	}
	
	public boolean login(User u) {
		String sql = "SELECT * FROM msg_user WHERE username=? AND pwd=? AND locked=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, u.getUsername());
			ps.setString(2, u.getPassword());
			ps.setBoolean(3, false);
			rs = ps.executeQuery();
			if(rs.next())
				return true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DB.close(rs);
			DB.close(ps);
			DB.close(conn);
		}
		return false;
	}

	public boolean register(User u) {
		String sql = "INSERT INTO msg_user(username, pwd, createTime, locked) values(?, ?, ?, ?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, u.getUsername());
			ps.setString(2, u.getPassword());
			ps.setLong(3, new Date().getTime());
			ps.setBoolean(4, false);
			ps.executeUpdate();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DB.close(ps);
			DB.close(conn);
		}
		
		return false;
	}

	public boolean check(String username) {
		String sql = "SELECT * FROM msg_user WHERE username=?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			rs = ps.executeQuery();
			if(rs.next()) 
				return true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DB.close(rs);
			DB.close(ps);
			DB.close(conn);
		}
		return false;
	}

}
